<?php

namespace App\Api\Controllers;


use App\Api\Request\ReplenishRequest;
use App\Logic\LogLogic;
use App\Models\SwtGood;
use App\Models\SwtMachineGood;
use App\Models\SwtMerchant;
use App\Models\SwtMerchantMachine;
use App\Models\SwtReplenish;
use App\Services\AdminService;
use Illuminate\Support\Facades\DB;

class ReplenishController extends BaseController
{
    public function finishReplenish(ReplenishRequest $request)
    {
        $id = $request->post('id');

        $info = SwtReplenish::with(['machine','replenish_good']) -> find($id);

        if($info -> status != 0) {
            return $this->error("补货单已完结");
        }

        Db::beginTransaction();
        try {
            $goods_log = [];

            foreach($info -> replenish_good as $v) {
                $goods = SwtMachineGood::where('machine_id', $info->machine->id) -> where('goods_id', $v -> goods_id) -> first();

                if($goods) {
                    $goods -> weight += $v -> replenish_num;

                    if($goods -> weight > $goods -> max_weight) {
                        $goods -> max_weight = $goods -> weight;
                    }

                    if($goods -> weight < 0) {
                        throw new \Exception('当前设备库存不足，无法退货');
                    }

                    $goods -> save();

                } else {
                    if($v -> replenish_num < 0) {
                        throw new \Exception('当前设备库存不足，无法退货');
                    }
                    $good_info = SwtGood::find($v -> goods_id);

                    $add_goods = [
                        'machine_id' => $info -> machine_id,
                        'goods_id'   => $v -> goods_id,
                        'max_weight' => $v -> replenish_num > 10 ? $v -> replenish_num : 10,
                        'weight'     => $v -> replenish_num,
                        'sell_price' => $good_info -> sell_price
                    ];

                    SwtMachineGood::create($add_goods);
                }

                $goods_log[] = [
                    'goods_name' => $v -> goods_name,
                    'num'        => $v -> replenish_num
                ];
            }

            $info -> admin_id = $this->admin_info['id'];

            $info -> status = 1;

            $info -> save();

            LogLogic::setMachineGoodsLogs($info -> machine_id, $info -> id, $goods_log, '后台进货');

            Db::commit();
            return $this->success();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e -> getMessage());
        }
    }

    public function cancelReplenish(ReplenishRequest $request)
    {
        $id = $request->post('id');

        $info = SwtReplenish::with(['machine']) -> find($id);

        if($info -> status != 0) {
            return $this->error("补货单已完结");
        }

        Db::beginTransaction();
        try {
            if($info -> merchant_id) {
                $deposit = SwtMerchantMachine::where('machine_id', $info->machine_id) -> where('merchant_id', $info->merchant_id) -> first();

                $merchant_info = SwtMerchant::find($info->merchant_id);

                $amount = $info -> amount;
                $deposit_now = $deposit -> deposit_now;
                $max_deposit = $merchant_info -> deposit;
                if($info -> amount > 0) {
                    if($deposit_now + $amount > $max_deposit) {
                        $deposit_now = $max_deposit;
                    } else {
                        $deposit_now += $amount;
                    }
                } else {
                    if($deposit_now - $amount < 0) {
                        $deposit_now = 0;
                    } else {
                        $deposit_now += $amount;
                    }
                }

                $deposit -> deposit_now = $deposit_now;

                $res = $deposit -> save();

                if(!$res) {
                    throw new \Exception('货款修改失败');
                }

                if($merchant_info -> shop_user_id) {
                    $params = [
                        'amount'       => $info->amount,
                        'shop_user_id' => $merchant_info->shop_user_id,
                        'type'         => $amount < 0 ? 0 : 1
                    ];

                    $res = AdminService::setDeviceDeposit($params);

                    if(!$res) {
                        throw new \Exception('同步货款失败');
                    }
                }
            }

            $info -> admin_id = $this->admin_info['id'];
            $info -> status = 2;
            $info -> save();

            Db::commit();
            return $this->success();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e -> getMessage());
        }

    }
}

